package com.dog.threesixty;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import com.dog.utils.Constants;
import com.dog.utils.Downloader;
import com.dog.utils.DownloadingItem;
import com.dog.utils.Utils;
import com.inapp.util.BillingService;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class PurchaseActivity extends Activity implements OnClickListener {

	private ImageView packView2;
	private ImageView packView3;
	private ImageView packView4;
	private ImageView packView5;

	private ImageView bundleView;

	private ImageView backButton;

	private ImageView imageView;

	private TextView titleView;
	private TextView descriptionView;

	private TextView priceView;
	private ImageView buyButton;
	private boolean isLevelUnlocked[] = new boolean[20];

	private int level;
	private String jsonFileName;
	private int unlockedLevels[];

	private String IMAGE_DIRECTORY = "";
	private String BASE_URL = "";

	private String BUNDLE_TEXT = "Get the lot at a discount price.Conformation,Muscles,Skeleton and Organs. Know EVERYTHING about your dog";
	private String PACK2_TEXT = "4 more levels on Confirmation.All the  cuteness in your dog is about his ears,nose,fur and tail.More Dogs...More cute:).";
	private String PACK3_TEXT = "Skeleton and Muscles are what really makes your dog work. Find out what makes your little do so fast or big dog so strong";

	private String PACK4_TEXT = "Deeper Muscles and Skull. Get a deeper knowledge of the canine by learning about the deeper muscles and features";
	private String PACK5_TEXT = "Teeth and Organs. Teeth could be the single most important feature in a Dogs life. Unlock 4 more crunching levels";

	private String BUNDLE_TITLE = "Pack Bundle - The lot";
	private String PACK2_TITLE = "Pack 2 - Conformation and Skeleton";
	private String PACK3_TITLE = "Pack 3 - Skeleton,Superficial Muscles";
	private String PACK4_TITLE = "Pack 4 - Deep Muscles,Skull";
	private String PACK5_TITLE = "Pack 5 - Tooth,Organs";

	private String title;
	private String description;
	private String priceText;

	private boolean isMainBundle;
	private int quiz;

	private String itemId;

	private TextView levelView1;
	private TextView levelView2;
	private TextView levelView3;
	private TextView levelView4;

	private String imageFileName[];

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		try {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.layout_purchase_screen);

			try {
				sharedPreferences = PreferenceManager
						.getDefaultSharedPreferences(this);
				sharedPreferences
						.registerOnSharedPreferenceChangeListener(ospcl);
			} catch (Exception e) {
				e.printStackTrace();
			}

			levelView1 = (TextView) findViewById(R.id.levelView1);

			levelView2 = (TextView) findViewById(R.id.levelView2);

			levelView3 = (TextView) findViewById(R.id.levelView3);

			levelView4 = (TextView) findViewById(R.id.levelView4);

			backButton = (ImageView) findViewById(R.id.backButton);
			backButton.setOnClickListener(this);

			imageView = (ImageView) findViewById(R.id.imageView);

			priceView = (TextView) findViewById(R.id.priceView);

			buyButton = (ImageView) findViewById(R.id.buyButton);
			buyButton.setOnClickListener(this);

			titleView = (TextView) findViewById(R.id.titleView);

			descriptionView = (TextView) findViewById(R.id.descriptionView);

			packView2 = (ImageView) findViewById(R.id.packView2);
			packView2.setOnClickListener(this);

			packView3 = (ImageView) findViewById(R.id.packView3);
			packView3.setOnClickListener(this);

			packView4 = (ImageView) findViewById(R.id.packView4);
			packView4.setOnClickListener(this);

			packView5 = (ImageView) findViewById(R.id.packView5);
			packView5.setOnClickListener(this);

			bundleView = (ImageView) findViewById(R.id.bundleView);
			bundleView.setOnClickListener(this);

			if (!Utils.isDeviceOnline(this)) {
				Utils.showAlertMessage(this,
						android.R.drawable.ic_dialog_alert,
						"Connection error ! !",
						"This package requires an internet connection to complete");
			} else {
				priceView.setVisibility(View.VISIBLE);
				priceView.setText("$1.99");
				buyButton.setVisibility(View.VISIBLE);
			}

			level = getIntent().getIntExtra(Constants.KEY_LEVEL, 4);
			levelWiseOperation(level);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			quiz = getIntent().getIntExtra(Constants.KEY_QUIZ, 1);
			if (quiz == Constants.QUIZ_LEARNING) {
				Intent intent = new Intent(PurchaseActivity.this,
						LearningBeforeActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
			} else {
				Intent intent = new Intent(PurchaseActivity.this,
						RecallBeforeActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private SharedPreferences sharedPreferences;
	private final OnSharedPreferenceChangeListener ospcl = new OnSharedPreferenceChangeListener() {

		public void onSharedPreferenceChanged(final SharedPreferences sp,
				String key) {
			try {
				if (BillingService.KEY_IN_APP_PURCHASED_ITEM_CHANGED_TIME
						.equals(key)) {
					runOnUiThread(new Runnable() {
						public void run() {
							try {
								if (BillingService.isPurchased(
										sharedPreferences, itemId)) {
									if (!isMainBundle) {
										downloadImage();
									} else {
										downloadAllImages();
									}
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					});
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	private void downloadImage() {
		try {

			if (IMAGE_DIRECTORY != null && imageFileName != null
					&& BASE_URL != null) {
				List<DownloadingItem> downloadingItems = new ArrayList<DownloadingItem>();

				if (!Utils.containsAllFiles(IMAGE_DIRECTORY,
						Arrays.asList(imageFileName))) {
					DownloadingItem di = new DownloadingItem();
					di.setBASE_URL(BASE_URL);
					di.setIMAGE_DIRECTORY(IMAGE_DIRECTORY);
					di.setImageFileName(imageFileName);
					downloadingItems.add(di);
				}
				if (downloadingItems.size() > 0) {
					Utils.downloadFiles(PurchaseActivity.this,
							downloadingItems, null);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onDestroy() {
		try {
			if (sharedPreferences != null && ospcl != null) {
				sharedPreferences
						.unregisterOnSharedPreferenceChangeListener(ospcl);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.onDestroy();
	}

	private void levelWiseOperation(int level) {
		switch (level) {
		case 4:
		case 5:
		case 6:
		case 7:
			isMainBundle = false;
			priceText = "$1.99";
			title = PACK2_TITLE;
			description = PACK2_TEXT;
			IMAGE_DIRECTORY = Constants.PACK2_DIRECTORY;
			jsonFileName = Constants.PACK2_JSON_FILE;
			imageFileName = getImageFileName(jsonFileName);
			BASE_URL = Constants.PACK2_STANDARD_URL;
			imageView.setImageResource(R.drawable.iap_pack2);
			itemId = Constants.PACK2_ITEM_ID;
			levelView1.setText("Conformation 2");
			levelView2.setText("Skeleton 1");
			levelView3.setText("Conformation 3");
			levelView4.setText("Conformation 4");
			break;

		case 8:
		case 9:
		case 10:
			isMainBundle = false;
			priceText = "$1.99";
			title = PACK3_TITLE;
			description = PACK3_TEXT;
			IMAGE_DIRECTORY = Constants.PACK3_DIRECTORY;
			jsonFileName = Constants.PACK3_JSON_FILE;
			imageFileName = getImageFileName(jsonFileName);
			BASE_URL = Constants.PACK3_STANDARD_URL;
			imageView.setImageResource(R.drawable.iap_pack3);
			itemId = Constants.PACK3_ITEM_ID;

			levelView1.setText("Skeleton 2");
			levelView2.setText("Super.Muscles 1");
			levelView3.setText("Super.Muscles 2");
			levelView4.setText("");
			break;

		case 11:
		case 12:
		case 13:
			isMainBundle = false;
			priceText = "$1.99";
			title = PACK4_TITLE;
			description = PACK4_TEXT;
			BASE_URL = Constants.PACK4_STANDARD_URL;
			IMAGE_DIRECTORY = Constants.PACK4_DIRECTORY;
			jsonFileName = Constants.PACK4_JSON_FILE;
			imageFileName = getImageFileName(jsonFileName);
			imageView.setImageResource(R.drawable.iap_pack4);
			itemId = Constants.PACK4_ITEM_ID;

			levelView1.setText("Deep Muscles 1");
			levelView2.setText("Deep Muscles 2");
			levelView3.setText("Skull");
			levelView4.setText("");
			break;

		case 14:
		case 15:
		case 16:
			isMainBundle = false;
			priceText = "$1.99";
			title = PACK5_TITLE;
			description = PACK5_TEXT;
			BASE_URL = Constants.PACK5_STANDARD_URL;
			IMAGE_DIRECTORY = Constants.PACK5_DIRECTORY;
			jsonFileName = Constants.PACK5_JSON_FILE;
			imageFileName = getImageFileName(jsonFileName);
			imageView.setImageResource(R.drawable.iap_pack5);
			itemId = Constants.PACK5_ITEM_ID;

			levelView1.setText("Teeth");
			levelView2.setText("Organs 1");
			levelView3.setText("Organs 2");
			levelView4.setText("");
			break;
		default:
			isMainBundle = true;
			imageView.setImageResource(R.drawable.bundle_pack);
			priceText = "$7.49";
			title = BUNDLE_TITLE;
			description = BUNDLE_TEXT;
			IMAGE_DIRECTORY = Constants.PACK2_DIRECTORY;
			jsonFileName = Constants.PACK2_JSON_FILE;
			imageFileName = getImageFileName(jsonFileName);
			BASE_URL = Constants.PACK2_STANDARD_URL;
			itemId = Constants.BUNDLE_ITEM_ID;

			levelView1.setText("Everything");
			levelView2.setText("");
			levelView3.setText("");
			levelView4.setText("");
			break;
		}

		titleView.setText(title);
		descriptionView.setText(description);
		priceView.setText(priceText);

	}

	private String[] getImageFileName(String jsonFileName) {
		String imageFileName[] = null;
		try {
			JSONObject jo = new JSONObject(new String(Utils.getFileData(
					PurchaseActivity.this, jsonFileName)));
			JSONArray ja = jo.getJSONObject("root").getJSONArray("dog");
			imageFileName = new String[ja.length()];
			for (int i = 0; i < ja.length(); i++) {
				imageFileName[i] = ja.getJSONObject(i).getString("-part");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return imageFileName;

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.packView2:
			levelWiseOperation(4);
			break;
		case R.id.packView3:
			levelWiseOperation(8);
			break;
		case R.id.packView4:
			levelWiseOperation(11);
			break;
		case R.id.packView5:
			levelWiseOperation(14);
			break;
		case R.id.bundleView:
			levelWiseOperation(0);
			break;
		case R.id.buyButton:
			boolean pack2Downloaded = BillingService.isPurchased(
					sharedPreferences, Constants.PACK2_ITEM_ID);
			boolean pack3Downloaded = BillingService.isPurchased(
					sharedPreferences, Constants.PACK3_ITEM_ID);
			boolean pack4Downloaded = BillingService.isPurchased(
					sharedPreferences, Constants.PACK4_ITEM_ID);
			boolean pack5Downloaded = BillingService.isPurchased(
					sharedPreferences, Constants.PACK5_ITEM_ID);

			boolean isAnyPackDownloaded = pack2Downloaded || pack3Downloaded
					|| pack4Downloaded || pack5Downloaded;
			if (isAnyPackDownloaded
					&& (!itemId.equalsIgnoreCase(Constants.BUNDLE_ITEM_ID))) {
				buyPopup();
			}
			
			break;

		case R.id.backButton:
			quiz = getIntent().getIntExtra(Constants.KEY_QUIZ, 1);
			if (quiz == Constants.QUIZ_LEARNING) {
				Intent intent = new Intent(PurchaseActivity.this,
						LearningBeforeActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
			} else {
				Intent intent = new Intent(PurchaseActivity.this,
						RecallBeforeActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
			}
			break;

		default:
			break;
		}

	}

	private void buyPopup() {
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Confirm Your In App Purchase");
		builder.setMessage(
				"Do you want to to buy one " + title + " for " + priceText)
				.setCancelable(false)
				.setPositiveButton("Buy",
						new DialogInterface.OnClickListener() {
							public void onClick(final DialogInterface dialog,
									final int id) {
								dialog.cancel();

								HomeScreenActivity.requestPurchase(
										sharedPreferences, itemId);

								// if (!isMainBundle) {
								// downloadImage();
								// } else {
								// downloadAllImages();
								// }

							}
						})
				.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int arg1) {
								dialog.cancel();

							}
						});

		final AlertDialog alert = builder.create();
		alert.show();
	}

	private void downloadAllImages() {

		try {
			List<DownloadingItem> downloadingItems = new ArrayList<DownloadingItem>();
			if (!Utils.containsAllFiles("pack2",
					Arrays.asList(getImageFileName("Pack2List.json")))) {
				DownloadingItem di = new DownloadingItem();
				di.setBASE_URL(Constants.PACK2_STANDARD_URL);
				di.setIMAGE_DIRECTORY("pack2");
				di.setImageFileName(getImageFileName("Pack2List.json"));
				downloadingItems.add(di);
			}
			if (!Utils.containsAllFiles("pack3",
					Arrays.asList(getImageFileName("Pack3List.json")))) {
				DownloadingItem di = new DownloadingItem();
				di.setBASE_URL(Constants.PACK3_STANDARD_URL);
				di.setIMAGE_DIRECTORY("pack3");
				di.setImageFileName(getImageFileName("Pack3List.json"));
				downloadingItems.add(di);
			}
			if (!Utils.containsAllFiles("pack4",
					Arrays.asList(getImageFileName("Pack4List.json")))) {
				DownloadingItem di = new DownloadingItem();
				di.setBASE_URL(Constants.PACK4_STANDARD_URL);
				di.setIMAGE_DIRECTORY("pack4");
				di.setImageFileName(getImageFileName("Pack4List.json"));
				downloadingItems.add(di);
			}
			if (!Utils.containsAllFiles("pack5",
					Arrays.asList(getImageFileName("Pack5List.json")))) {
				DownloadingItem di = new DownloadingItem();
				di.setBASE_URL(Constants.PACK5_STANDARD_URL);
				di.setIMAGE_DIRECTORY("pack5");
				di.setImageFileName(getImageFileName("Pack5List.json"));
				downloadingItems.add(di);
			}

			if (downloadingItems.size() > 0) {
				Utils.downloadFiles(PurchaseActivity.this, downloadingItems,
						null);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		// try {
		// new AsyncTask<String, String, String>() {
		// private ProgressDialog progressDialog;
		// private int imageIndex = 0;
		// private int totalFiles;
		// private int count = 0;
		//
		// private JSONObject packList2;
		// private JSONObject packList3;
		// private JSONObject packList4;
		// private JSONObject packList5;
		//
		// private JSONArray jaPack2;
		// private JSONArray jaPack3;
		// private JSONArray jaPack4;
		// private JSONArray jaPack5;
		//
		// @Override
		// protected void onPreExecute() {
		// try {
		//
		// packList2 = new JSONObject(new String(
		// Utils.getFileData(PurchaseActivity.this,
		// "Pack2List.json")));
		// jaPack2 = packList2.getJSONObject("root").getJSONArray(
		// "dog");
		//
		// packList3 = new JSONObject(new String(
		// Utils.getFileData(PurchaseActivity.this,
		// "Pack3List.json")));
		// jaPack3 = packList3.getJSONObject("root").getJSONArray(
		// "dog");
		//
		// packList4 = new JSONObject(new String(
		// Utils.getFileData(PurchaseActivity.this,
		// "Pack4List.json")));
		// jaPack4 = packList4.getJSONObject("root").getJSONArray(
		// "dog");
		//
		// packList5 = new JSONObject(new String(
		// Utils.getFileData(PurchaseActivity.this,
		// "Pack5List.json")));
		// jaPack5 = packList2.getJSONObject("root").getJSONArray(
		// "dog");
		//
		// totalFiles = jaPack2.length() + jaPack3.length()
		// + jaPack4.length() + jaPack5.length();
		//
		// unlockedLevels = new int[18];
		//
		// progressDialog = new ProgressDialog(
		// PurchaseActivity.this);
		// progressDialog.setMessage("Downloading....");
		// progressDialog.setIndeterminate(false);
		// progressDialog.setCancelable(true);
		// progressDialog.setMax(totalFiles);
		// progressDialog
		// .setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		//
		// progressDialog.show();
		//
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		// }
		//
		// protected void onProgressUpdate(String... arg0) {
		// try {
		// progressDialog.setProgress(imageIndex);
		// count++;
		// if (imageIndex == jaPack2.length()) {
		// count = 0;
		// unlockedLevels[0] = 4;
		// unlockedLevels[1] = 5;
		// unlockedLevels[2] = 6;
		// unlockedLevels[3] = 7;
		//
		// IMAGE_DIRECTORY = "pack3";
		// jsonFileName = "Pack3List.json";
		// BASE_URL = Constants.PACK2_STANDARD_URL;
		// Utils.setImageDownloaded(PurchaseActivity.this,
		// Constants.IS_PACK_DOWNLOADED + 2, true);
		//
		// }
		// if (imageIndex == (jaPack2.length() + jaPack3.length())) {
		// count = 0;
		// unlockedLevels[4] = 8;
		// unlockedLevels[5] = 9;
		// unlockedLevels[6] = 10;
		//
		// IMAGE_DIRECTORY = "pack4";
		// jsonFileName = "Pack4List.json";
		// BASE_URL = Constants.PACK4_STANDARD_URL;
		// Utils.setImageDownloaded(PurchaseActivity.this,
		// Constants.IS_PACK_DOWNLOADED + 3, true);
		//
		// }
		//
		// if (imageIndex == (jaPack2.length() + jaPack3.length() + jaPack4
		// .length())) {
		// count = 0;
		// unlockedLevels[7] = 11;
		// unlockedLevels[8] = 12;
		// unlockedLevels[9] = 13;
		//
		// IMAGE_DIRECTORY = "pack5";
		// jsonFileName = "Pack5List.json";
		// BASE_URL = Constants.PACK5_STANDARD_URL;
		// Utils.setImageDownloaded(PurchaseActivity.this,
		// Constants.IS_PACK_DOWNLOADED + 4, true);
		//
		// }
		//
		// if (imageIndex == totalFiles) {
		// Toast.makeText(PurchaseActivity.this,
		// "Download completed", Toast.LENGTH_SHORT)
		// .show();
		// count = 0;
		// unlockedLevels[10] = 14;
		// unlockedLevels[11] = 15;
		// unlockedLevels[12] = 16;
		// Utils.setImageDownloaded(PurchaseActivity.this,
		// Constants.IS_PACK_DOWNLOADED + 5, true);
		//
		// }
		// for (int i = 0; i < unlockedLevels.length; i++) {
		// Utils.putLevelUnlocked(PurchaseActivity.this,
		// Constants.KEY_LEVEL_UNLOCKED
		// + unlockedLevels[i], true);
		// }
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		// }
		//
		// @Override
		// protected String doInBackground(String... arg0) {
		// try {
		// while (imageIndex < totalFiles) {
		//
		// JSONObject job = new JSONObject(new String(
		// Utils.getFileData(PurchaseActivity.this,
		// jsonFileName)));
		// JSONArray jar = job.getJSONObject("root")
		// .getJSONArray("dog");
		// Log.i("DREG", "JSON File Name = " + jsonFileName
		// + " Json String =" + jar.toString());
		//
		// String fileName = jar.getJSONObject(imageIndex)
		// .getString("-part");
		//
		// String url = Constants.PACK1_STANDARD_URL
		// + Utils.getAndroidFormattedUrl(fileName)
		// + ".png";
		// fileName = fileName + ".png";
		// // Log.i("DREG", "File Name=" + fileName);
		// // Log.i("DREG", "Url =" + url);
		// Downloader.downloadFile(IMAGE_DIRECTORY, fileName,
		// url, PurchaseActivity.this);
		// imageIndex++;
		// publishProgress("");
		// }
		//
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		// return null;
		// }
		//
		// @Override
		// protected void onPostExecute(String unused) {
		// progressDialog.dismiss();
		//
		// }
		// }.execute();
		//
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
	}

}
